package com.shangma.cn.commons.utils;

import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 开发人员: 辉哥真球帅
 * 联系方式: zhengzhoudaxuevip@163.com
 * 创建时间: 2021/10/12  10:52
 * 文件含义:
 */
public class TreeUtils {


    public static <T> void buildTreeData(List<T> root, List<T> list) {
        //排序
        List<T> collectList = root.stream().sorted((t1, t2) -> {
            int sort1 = (int) ReflectionUtils.getFieldValue(t1, "sort");
            int sort2 = (int) ReflectionUtils.getFieldValue(t2, "sort");
            return sort1 - sort2;
        }).collect(Collectors.toList());
        root.clear();
        root.addAll(collectList);
        root.forEach(t -> getChildren(t, list));
    }

    public static <T> void getChildren(T t, List<T> list) {
        List<T> children = list.stream().filter(t1 -> ReflectionUtils.getFieldValue(t1, "parentId").equals(ReflectionUtils.getFieldValue(t, "id"))).collect(Collectors.toList());
        List<T> sortChildren = children.stream().sorted((t1, t2) -> {
            int sort1 = (int) ReflectionUtils.getFieldValue(t1, "sort");
            int sort2 = (int) ReflectionUtils.getFieldValue(t2, "sort");
            return sort1 - sort2;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(sortChildren)) {
            ReflectionUtils.setFieldValue(t, "children", sortChildren);
            //遍历孩子
            sortChildren.forEach((t3 -> getChildren(t3, list)));
        }


    }
}
